package com.xy_pro.xymanager.service;

import com.xy_pro.xymanager.auth.dto.LoginRequest;
import com.xy_pro.xymanager.auth.dto.LoginResponse;
import com.xy_pro.xymanager.auth.security.JwtTokenProvider;
import com.xy_pro.xymanager.auth.security.UserDetailsImpl;
import com.xy_pro.xymanager.entity.UserEntity;
import com.xy_pro.xymanager.exception.AuthenticationException;
import com.xy_pro.xymanager.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final UserRepository userRepository;
    private final PasswordEncoder encoder;
    private final JwtTokenProvider tokenProvider;

    @SneakyThrows
    public LoginResponse login(LoginRequest loginRequest) {
        // 验证用户名和密码
        try {
            if(loginRequest.getUsername() == null || loginRequest.getPassword() == null) {
//                throw new BadCredentialsException("用户名和密码不能为空！");
            }
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()
                    )
            );

            // 设置安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = tokenProvider.generateJwtToken(authentication);

            // 获取用户信息
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            UserEntity user = userRepository.findById(userDetails.getId()).orElseThrow();
//
//            // 返回用户信息（不包含密码）
//            UserEntity userEntity = new UserEntity();
//            userEntity.setName(user.getName());
//            userEntity.setId(user.getId());
//            userEntity.setName(user.getName());
//            userEntity.setPhone(user.getPhone());
//            userEntity.setAge(user.getAge());

            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setUserName(userDetails.getUsername());
            loginResponse.setToken(jwt);

            return loginResponse;

        } catch (BadCredentialsException e){
            throw new AuthenticationException("用户名密码不正确");
        } catch (UsernameNotFoundException e){
            throw new AuthenticationException("用户名不存在");
        } catch (Exception e){
            throw new AuthenticationException("认证失败！" + e.getMessage());
        }
    }
}
